<template>
  <div class="wrap">
    <a-select v-bind="bindProps" @change="onChange" @search="onSearch" />
    <a-button
      shape="circle"
      @click="rfidClick"
      style="display: flex; justify-content: center; align-items: center; margin-left: 6px"
      :loading="loading"
    >
      <template #icon><Icon icon="rfid|svg" :size="28" /></template>
    </a-button>
    <!-- <a-select v-bind="bindProps" @change="onChange" /> -->
  </div>
  <div v-if="false" class="ant-form-item-explain-error">{{ t('component.rfidSelect.tip') }} </div>
</template>

<script lang="ts">
  import { defineComponent, ref, computed, onMounted } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { getAuthorTag } from '@/api/asset/assetInfo';
  import { Button } from 'ant-design-vue';
  import { list } from '@/views/device/tag-management/TagManagement.api';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { t } = useI18n();
  // 可以输入的下拉框（此组件暂时没有人用）
  export default defineComponent({
    name: 'JSelectInput',
    components: { 'a-button': Button },
    emits: ['change', 'update:value'],
    setup(props, { emit, attrs }) {
      // 内部 options 选项
      const options = ref<any[]>([]);
      // 监听外部 options 变化，并覆盖内部 options
      // 合并 props 和 attrs
      const bindProps: any = computed(() =>
        Object.assign(
          {
            showSearch: true,
          },
          props,
          attrs,
          {
            options: options.value,
          }
        )
      );

      function onChange(...args: any[]) {
        deleteSearchAdd(args[0]);
        emit('change', ...args);
        emit('update:value', args[0]);
      }

      function onSearch(value) {
        // 是否找到了对应的项，找不到则添加这一项
        let foundIt =
          options.value.findIndex((option) => {
            return option.value.toString() === value.toString();
          }) !== -1;
        // !!value ：不添加空值
        if (!foundIt && !!value) {
          deleteSearchAdd(value);
          // searchAdd 是否是通过搜索添加的
          options.value.push({ value: value, searchAdd: true });
          //onChange(value,{ value })
        } else if (foundIt) {
          onChange(value);
        }
      }

      // 删除无用的因搜索（用户输入）而创建的项
      function deleteSearchAdd(value = '') {
        let indexes: any[] = [];
        options.value.forEach((option, index) => {
          if (option.searchAdd) {
            if ((option.value ?? '').toString() !== value.toString()) {
              indexes.push(index);
            }
          }
        });
        // 翻转删除数组中的项
        for (let index of indexes.reverse()) {
          options.value.splice(index, 1);
        }
      }
      onMounted(() => {
        list({ pageSize: -1 }).then((res) => {
          console.log(res, 'lllllllllllll');

          options.value = res.records.map(({ tagId }) => ({ value: tagId }));
        });
      });
      const msg = useMessage();
      const loading = ref(false);
      function rfidClick() {
        loading.value = true;
        msg.createMessage.success('正在扫描 ... ');
        getAuthorTag({})
          .then((res) => {
            console.log(res, 'getAuthorTag');
            if (res) {
              emit('change', res);
              emit('update:value', res);
              msg.createMessage.success('扫描完成,已添加' + res);
            } else {
              res = 'TEST' + (parseInt(Math.random() * 100000) + 100000);
              emit('change', res);
              emit('update:value', res);
            }
          })
          .finally(() => {
            loading.value = false;
          });
      }
      return {
        t,
        bindProps,
        onChange,
        onSearch,
        rfidClick,
        loading,
      };
    },
  });
</script>

<style scoped lang="less">
  .wrap {
    display: flex;
    align-items: center;
    z-index: 1000;
  }
</style>
